package com.zwq.springbootlearn.aspect;

import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: zwq
 * Create in 2018/6/30 15:16
 */
@Component
@Aspect   //切面
public class HttpAspect {

    //定义一个Logger
    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    //定义一个切入点
    @Pointcut("execution(* com.zwq.springbootlearn.controller.GirlController.*(..))")
    public void log(){}

    //before通知
    @Before("log()")
    public void before(JoinPoint jp){
        //logger.info("before advice");

        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attr.getRequest();

        //拦截所有请求
        //url
        logger.info("url={}",request.getRequestURL());

        //method
        logger.info("method={}",request.getMethod());

        //ip
        logger.info("ip={}",request.getRemoteAddr());

        //类方法
        logger.info("class.method={}",jp.getSignature().getDeclaringTypeName() +"."+ jp.getSignature().getName());

        //方法参数
        logger.info("args=",jp.getArgs());
    }

    //after通知
    @After("log()")
    public void after(){
        logger.info("after advice");
    }

    @AfterReturning(returning = "obj", pointcut = "log()")
    public void doafter(Object obj){
        logger.info("response={}",obj.toString());
    }
}
